
package classes;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;


public class ViewPatientRecordPanel extends JPanel {
    
    PatientManagement patientController = new PatientManagement();
    Vector<String> serviceList = new Vector<String>();
    Vector<String> header = new Vector<String>();
    
    DefaultTableModel recordsTableModel;
    JTable Records = new JTable(null,header);
    
    Color error_color = Color.PINK;
    Color default_color = Color.WHITE;
    
    JLabel lblPanelTitle = new JLabel("Patient Information");
    JLabel lblTableTitle = new JLabel("Dental Records");
    
    JButton btnAddService = new JButton("Add", new ImageIcon(getClass().getResource("/images/add.png")));
    JButton btnEditService = new JButton("Edit", new ImageIcon(getClass().getResource("/images/edit.png")));
    JButton btnClosePanel = new JButton("Close", new ImageIcon(getClass().getResource("/images/cancel.png")));
    
    JScrollPane scrollPane = new JScrollPane(Records);
    
    JLabel lblPatientNo = new JLabel("Patient Number:");
    JLabel lblPatientNoValue = new JLabel();
    JLabel lblLastName = new JLabel("Last Name:"); 
    JLabel lblFirstName = new JLabel("First Name:");
    JLabel lblMiddleName = new JLabel("Middle Initial:");
    JLabel lblAddress = new JLabel("Address:");
    JLabel lblAge = new JLabel("Age:");
    JLabel lblGender = new JLabel("Gender:");
    JLabel lblContactNo = new JLabel("Contact Number:");
   
    JTextField txtLastName = new JTextField();
    JTextField txtFirstName = new JTextField();
    JTextField txtMiddleName = new JTextField();
    JTextField txtAge = new JTextField();
    JTextField txtContactNo = new JTextField();
    
    JTextArea txtAddress = new JTextArea();
    JScrollPane scrollAddress = new JScrollPane(txtAddress);
    
    String[] Genders = {"Male", "Female"};
    
    JComboBox selectGender = new JComboBox(Genders);
    
    JButton btnSubmit = new JButton("Submit", new ImageIcon(getClass().getResource("/images/ok.png"))); 
    JButton btnEdit = new JButton("Edit", new ImageIcon(getClass().getResource("/images/edit.png"))); 
    
    JSeparator separator = new JSeparator();
    
    JButton btnReset = new JButton("Cancel", new ImageIcon(getClass().getResource("/images/reset.png")));
    
    public ViewPatientRecordPanel() {
        //panel layout
        setLayout(null);
        setSize(740,655);
        setVisible(false);
        setOpaque(false);
        
        //add to panel
        add(lblPanelTitle);
        add(lblTableTitle);
        add(btnAddService);
        add(btnEditService);
        add(btnClosePanel);
        add(scrollPane);
        add(lblLastName); 
        add(lblFirstName);
        add(lblMiddleName);
        add(lblAddress);
        add(lblAge);
        add(lblGender);
        add(lblContactNo);
        add(txtLastName);
        add(txtFirstName);
        add(txtMiddleName);
        add(txtAge);
        add(scrollAddress);
        add(txtContactNo);
        add(selectGender);
        add(btnSubmit);
        add(btnEdit);
        add(lblPatientNo);
        add(lblPatientNoValue);
        add(separator);
        add(btnReset);
        
        //set font
        lblPanelTitle.setFont(new Font("Century Gothic", Font.BOLD, 16));
        lblTableTitle.setFont(new Font("Century Gothic", Font.BOLD, 16));
        btnAddService.setFont(new Font("Century Gothic", Font.BOLD, 14));
        btnEditService.setFont(new Font("Century Gothic", Font.BOLD, 14));
        btnClosePanel.setFont(new Font("Century Gothic", Font.BOLD, 14));
        lblFirstName.setFont(new Font("Century Gothic", Font.BOLD, 14));
        lblLastName.setFont(new Font("Century Gothic", Font.BOLD, 14));
        lblMiddleName.setFont(new Font("Century Gothic", Font.BOLD, 14));
        lblAddress.setFont(new Font("Century Gothic", Font.BOLD, 14));
        lblAge.setFont(new Font("Century Gothic", Font.BOLD, 14));
        lblGender.setFont(new Font("Century Gothic", Font.BOLD, 14));
        lblContactNo.setFont(new Font("Century Gothic", Font.BOLD, 14));
        txtLastName.setFont(new Font("Century Gothic", Font.PLAIN, 14));
        txtFirstName.setFont(new Font("Century Gothic", Font.PLAIN, 14));
        txtMiddleName.setFont(new Font("Century Gothic", Font.PLAIN, 14)); 
        txtAge.setFont(new Font("Century Gothic", Font.PLAIN, 14)); 
        txtAddress.setFont(new Font("Century Gothic", Font.PLAIN, 14)); 
        txtContactNo.setFont(new Font("Century Gothic", Font.PLAIN, 14)); 
        selectGender.setFont(new Font("Century Gothic", Font.PLAIN, 14));  
        btnSubmit.setFont(new Font("Century Gothic", Font.BOLD, 14));
        btnEdit.setFont(new Font("Century Gothic", Font.BOLD, 14));
        lblPatientNo.setFont(new Font("Century Gothic", Font.BOLD, 14));
        lblPatientNoValue.setFont(new Font("Century Gothic", Font.BOLD, 14));
        btnReset.setFont(new Font("Century Gothic", Font.BOLD, 14));
        
        //set bounds
        lblPanelTitle.setBounds(20, 20, 150, 30);
        lblPatientNo.setBounds(20, 50, 150, 30);
        lblPatientNoValue.setBounds(140, 50, 150, 30);
       
        lblLastName.setBounds(20,80,150,30);
        txtLastName.setBounds(20,105,150,30);
        lblFirstName.setBounds(180,80,150,30);
        txtFirstName.setBounds(180,105,150,30);
        lblMiddleName.setBounds(340,80,150,30);
        txtMiddleName.setBounds(340,105,100,30);
        
        lblAddress.setBounds(20,135,150,30);
        scrollAddress.setBounds(20,160,200,100);
        scrollAddress.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        txtAddress.setLineWrap(true);
        
        lblAge.setBounds(440,135,150,30);
        txtAge.setBounds(440,160,50,30);
        
        lblGender.setBounds(255,135,150,30);
        selectGender.setBounds(255,160,150,30);
        
        lblContactNo.setBounds(255,205,150,30);
        txtContactNo.setBounds(255,230,150,30);
        
        btnSubmit.setBounds(20, 285, 105, 30);
        btnReset.setBounds(145, 285, 105, 30);
        btnEdit.setBounds(270, 285, 105, 30);
        
        btnAddService.setBounds(20, 600, 105, 30);
        btnEditService.setBounds(145, 600, 105, 30);
        btnClosePanel.setBounds(595, 600, 105, 30);
        
        lblTableTitle.setBounds(20, 330, 190, 30);
        separator.setBounds(0,325, 720,this.getHeight());
        
        scrollPane.setBounds(20,360,680,220);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

        
        disableEdit();
        
        btnEdit.addActionListener(new  ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                if(Main.frame.addService.isVisible()==false && Main.frame.editService.isVisible()==false)
                {
                    enableEdit();
                    btnEdit.setEnabled(false);
                }                
            }
        }
        );
        
        btnSubmit.addActionListener(new  ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                if(Main.frame.addService.isVisible()==false && Main.frame.editService.isVisible()==false)
                {                  
                    check();
                }
            }
        }
        );
        
         btnReset.addActionListener(new  ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                if(Main.frame.addService.isVisible()==false && Main.frame.editService.isVisible()==false)
                {                  
                    initValues();
                    disableEdit();
                    resetBG();
                }
            }
        }
        );
         
         //mouse listeners for the text fields
        txtLastName.addMouseListener( new MouseListener() {
             public void mousePressed(MouseEvent e) {
                txtLastName.setBackground(default_color);
             }
             public void mouseClicked(MouseEvent e) {}
             public void mouseReleased(MouseEvent e) {}
             public void mouseEntered(MouseEvent e) {}
             public void mouseExited(MouseEvent e) {}
         });
         
         txtFirstName.addMouseListener( new MouseListener() {
             public void mousePressed(MouseEvent e) {
                 txtFirstName.setBackground(default_color);
             }
             public void mouseClicked(MouseEvent e) {}
             public void mouseReleased(MouseEvent e) {}
             public void mouseEntered(MouseEvent e) {}
             public void mouseExited(MouseEvent e) {}
         });
         
         txtMiddleName.addMouseListener( new MouseListener() {
             public void mousePressed(MouseEvent e) {
                 txtMiddleName.setBackground(default_color);
             }
             public void mouseClicked(MouseEvent e) {}
             public void mouseReleased(MouseEvent e) {}
             public void mouseEntered(MouseEvent e) {}
             public void mouseExited(MouseEvent e) {}
         });
         
         txtAddress.addMouseListener( new MouseListener() {
             public void mousePressed(MouseEvent e) {
                 txtAddress.setBackground(default_color);
             }
             public void mouseClicked(MouseEvent e) {}
             public void mouseReleased(MouseEvent e) {}
             public void mouseEntered(MouseEvent e) {}
             public void mouseExited(MouseEvent e) {}
         });
         
         txtAge.addMouseListener( new MouseListener() {
             public void mousePressed(MouseEvent e) {
                 txtAge.setBackground(default_color);
             }
             public void mouseClicked(MouseEvent e) {}
             public void mouseReleased(MouseEvent e) {}
             public void mouseEntered(MouseEvent e) {}
             public void mouseExited(MouseEvent e) {}
         });
         
         txtContactNo.addMouseListener( new MouseListener() {
             public void mousePressed(MouseEvent e) {
                txtContactNo.setBackground(default_color);
             }
             public void mouseClicked(MouseEvent e) {}
             public void mouseReleased(MouseEvent e) {}
             public void mouseEntered(MouseEvent e) {}
             public void mouseExited(MouseEvent e) {}
         });
         header.add("Procedure ID");
         header.add("Service Category");
         header.add("Description");
         header.add("Tooth No.");
         header.add("Date");
         header.add("Price");
         setRecordsTable();
    }
    
      private JTable autoResizeColWidth(JTable table, DefaultTableModel model) {
        table.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
        table.setModel(model);

        int margin = 5;

        for (int i = 0; i < table.getColumnCount()-1; i++) {
            int                     vColIndex = i;
            DefaultTableColumnModel colModel  = (DefaultTableColumnModel) table.getColumnModel();
            TableColumn             col       = colModel.getColumn(vColIndex);
            int                     width     = 0;

            // Get width of column header
            TableCellRenderer renderer = col.getHeaderRenderer();

            if (renderer == null) {
                renderer = table.getTableHeader().getDefaultRenderer();
            }

            Component comp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0, 0);

            width = comp.getPreferredSize().width;

            // Get maximum width of column data
            for (int r = 0; r < table.getRowCount(); r++) {
                renderer = table.getCellRenderer(r, vColIndex);
                comp     = renderer.getTableCellRendererComponent(table, table.getValueAt(r, vColIndex), false, false,
                        r, vColIndex);
                width = Math.max(width, comp.getPreferredSize().width);
            }

            // Add margin
            width += 2 * margin;

            // Set the width
            col.setPreferredWidth(width);
        }

        ((DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer()).setHorizontalAlignment(
            SwingConstants.LEFT);

        // table.setAutoCreateRowSorter(true);
        table.getTableHeader().setReorderingAllowed(false);

        return table;
    }
    
     public void setRecordsTable() {
      serviceList = patientController.ViewAllServiceRendered(lblPatientNoValue.getText());
      recordsTableModel = new DefaultTableModel(serviceList, header)
                {
            @Override
                    public boolean isCellEditable(int row, int col)
                    {
                        return false;
                    }
                };
        
        Records.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        Records.setModel(recordsTableModel);
        autoResizeColWidth(Records,recordsTableModel);
     }
    
    public void initValues()
    {
        int row = Main.frame.managePatient.patientTable.getSelectedRow();    //get the index of the selected row
        int col = 0; //get the index of the selected column
        Patient patient = patientController.viewPatient(Main.frame.managePatient.patientTable.getModel().getValueAt(row, col).toString());
        txtLastName.setText(patient.getLastName());
        txtFirstName.setText(patient.getFirstName());
        txtMiddleName.setText(patient.getMiddleName());
        txtAge.setText(patient.getAge());
        txtAddress.setText(patient.getAddress());
        txtContactNo.setText(patient.getContactNo());
        selectGender.setSelectedItem(patient.getGender()); 
        lblPatientNoValue.setText(patient.getPatientNo());
    }
    
     public void disableEdit()
     {
        btnEdit.setEnabled(true);
        txtLastName.setEnabled(false);
        txtFirstName.setEnabled(false);
        txtMiddleName.setEnabled(false);
        txtAge.setEnabled(false);
        txtAddress.setEnabled(false);
        txtContactNo.setEnabled(false); 
        selectGender.setEnabled(false); 
        btnReset.setEnabled(false);
        btnSubmit.setEnabled(false);
     }
     
     private void enableEdit()
     {
        txtLastName.setEnabled(true);
        txtFirstName.setEnabled(true);
        txtMiddleName.setEnabled(true);
        txtAge.setEnabled(true);
        txtAddress.setEnabled(true);
        txtContactNo.setEnabled(true);
        selectGender.setEnabled(true);; 
        btnSubmit.setEnabled(true);
        btnReset.setEnabled(true);
     }
     
     public void check() {
        String pNo = lblPatientNoValue.getText();
        String lname = txtLastName.getText();
        String fname = txtFirstName.getText();
        String mname = txtMiddleName.getText();
        String age = txtAge.getText();
        String contact = txtContactNo.getText();
        String addrs = txtAddress.getText();
        String gender = selectGender.getSelectedItem().toString();
        boolean error = false;
        
        //check if the text fields are empty
        if(lname.length() <= 0 || lname.length() >= 30) {
            txtLastName.setBackground(error_color);
            error = true;
        }
        else {
            txtLastName.setBackground(default_color);
        }
        
        if(fname.length() <= 0 || fname.length() >=30) {
            txtFirstName.setBackground(error_color);
            error = true;
        }
        else {
            txtFirstName.setBackground(default_color);
        }
        
        if(mname.length() <= 0 || mname.length() >=30) {
            txtMiddleName.setBackground(error_color);
            error = true;
        }
        else {
            txtMiddleName.setBackground(default_color);
        }
        
        if(addrs.length() <= 0 || addrs.length() >=50) {
            txtAddress.setBackground(error_color);
            error = true;
        }
        else {
            txtAddress.setBackground(default_color);
        }
        
        try {
        if(age.length() <= 0 || Integer.parseInt(age) <= 0 || age.length() > 3) {
            txtAge.setBackground(error_color);
            error = true;
        }
        else {
            txtAge.setBackground(default_color);
        }
        }
        catch(Exception e)
        {
               txtAge.setBackground(error_color);
               error = true;
        }
        try {
        if(contact.length() <= 0 || Double.parseDouble(contact)<= 0 || contact.length()>= 15) {
            txtContactNo.setBackground(error_color);
            error = true;
        }
        else {
            txtContactNo.setBackground(default_color);
        }
        }
        catch(Exception e)
        {
            txtContactNo.setBackground(error_color);
            error = true;
        }
        
        
        if(error == true)
        {
            JOptionPane.showMessageDialog(this, "Please be sure to fill up the form correctly", "Error Message", JOptionPane.ERROR_MESSAGE);    
        }
        else if(error == false) {
            
            if(patientController.checkPatientOverlap(lname,fname,mname,pNo) == true) {
            JOptionPane.showMessageDialog(this, "Patient information overlaps with another patient.", "Error Message", JOptionPane.ERROR_MESSAGE);
       
            }
            else {
            int response = JOptionPane.showConfirmDialog(null, "Are you sure?", "Confirm",
            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
            if (response == JOptionPane.YES_OPTION) {
               patientController.EditPatient(lname, fname, mname, addrs, age, gender, contact, pNo);
               JOptionPane.showMessageDialog(this, "Patient Information was successfully updated.", "Message", JOptionPane.INFORMATION_MESSAGE); 
               btnEdit.setEnabled(true);
               disableEdit();
            }
          }
        }
        
        
    }
    
    public void resetBG() {
        txtLastName.setBackground(default_color);
        txtFirstName.setBackground(default_color);
        txtMiddleName.setBackground(default_color);
        txtAge.setBackground(default_color);
        txtContactNo.setBackground(default_color);
        txtAddress.setBackground(default_color);
    }
     
     //checker if there is a selected item in the table
     public boolean isTableSelected(){
         if(Records.getSelectedColumn() != -1 && Records.getSelectedRow() != -1){
             return true;
         }
         else
             return false;
     }
   
}
